<template>
  <!-- 城市联动 -->
  <el-form-item class="city_select" label="城市:" prop="status">
    <el-select v-model="province" placeholder="请选择" @change="provinceChanged">
      <el-option v-for="item in provinces" :key="item.code" :label="item.name" :value="item.code"></el-option>
    </el-select>
    <el-select v-model="city" :loading="loadingCity" @change="cityChanged" placeholder="请选择">
      <el-option v-for="item in cities" :key="item.code" :label="item.name" :value="item.code"></el-option>
    </el-select>
  </el-form-item>
</template>
<script>
import provinceCity from '@/assets/provinceCity/provinceCity.json'
export default {
  name: 'city',
  props: {
    // 城市联动
    provinceCode: {
      type: String,
      default: ''
    },
    cityCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 城市联动
      loadingCity: false,
      provinces: [],
      cities: [],
      province: '',
      city: ''
    }
  },
  computed: {},
  watch: {},
  methods: {
    // 城市联动 省份发生改变
    provinceChanged(value) {
      if (value !== '') {
        this.loadingCity = true
        for (var item of this.provinces) {
          if (item.code === value) {
            this.cities = item.cities
            this.city = this.cities[0]
            this.loadingCity = false
            break
          } else {
            continue
          }
        }
      } else {
        this.cities = []
        this.city = ''
      }
      this.$emit('selectChange', this.province, this.city)
    },
    // 城市联动 城市发生改变
    cityChanged(value) {
      this.$emit('selectChange', this.province, this.city)
    },
    resetProviceCity(province, city) {
      this.cities = []
      if (province && city) {
        this.province = province
        this.provinceChanged(this.province)
        this.city = city
      } else {
        this.province = ''
        this.city = ''
      }
    }
  },
  created() {
    this.provinces = provinceCity.provinces
  },
  mounted() {
    this.province = this.provinceCode
    this.provinceChanged(this.provinceCode)
    this.city = this.cityCode
  }
}
</script>

<style lang='less' scoped>
.city_select {
  /deep/.el-input__inner,
  .el-select {
    margin-right: 1px;
    width: 110px;
  }
}
</style>
